#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#define FORMAT "[%s@%s %s]#"

int g_argc=0;
char* g_argv[128];

const char* GetUserName()
{
    const char* name=getenv("USER");
    return name==NULL?"None":name;
}
const char* GetHostName()
{
    const char* hostname=getenv("HOSTNAME");
    return hostname==NULL?"None":hostname; 
}
const char* GetPwd()
{
    const char* pwd=getenv("PWD");
    return pwd==NULL?"None":pwd;
}

void MakeCommandLine(char CmdPrompt[],int size)
{
    snprintf(CmdPrompt,size,FORMAT,GetUserName(),GetHostName(),GetPwd());
}
void PrintCommandPrompt()
{
    char prompt[1024];
    MakeCommandLine(prompt,sizeof(prompt));
    printf("%s",prompt);
    fflush(stdout);
}
bool GetCommandline(char* out,int size)
{
    //ls -l ---> "ls -l\n" 字符串
    char* c=fgets(out,size,stdin);
    if(c==NULL)
        return false;
    out[strlen(out)-1]=0;
    if(strlen(out)==0)
        return false;
    return true;
}
bool CommandParse(char* commandline)
{
    //"ls -l" ---> "ls" "-l"
    #define SEP " "
    g_argc=0;
    g_argv[g_argc++]=strtok(commandline,SEP);
    while((bool)g_argv[g_argc++]=strtok(nullptr,SEP));
    g_argc--;
    return true;
}
void Execute()
{

    pid_t id=fork();
    if(id==0)
    {
        //5.子进程进行程序替换
        execvp(g_argv[0],g_argv);
        exit(1);
    }
    pid_t rid=waitpid(id,NULL,0);
}

int main()
{
    while(true)
    {
        //1.输出命令行提示符
        PrintCommandPrompt();
        //2.获取用户输入指令
        char commandline[1024];
        if(!GetCommandline(commandline,sizeof(commandline)))
            continue;
        //3.命令行分析
        CommandParse(commandline);
        //4.执行命令
        Execute();
    }
    return 0;
}
